package httpflv

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"strings"
	"xmediaEmu/pkg/decoder/codec"
	"xmediaEmu/pkg/log"
)

var flvHttpResponseHeader []byte

// 不支持https.
type Server struct {
	// Addr string // http address.
	handler codec.Handler
}

func NewServer(h codec.Handler) *Server {
	return &Server{
		handler: h,
	}
}

// HandleConn 建立http-flv的http 连接.
// gin框架兼容, 基于gin框架注册回调函数.
func (server *Server) HandleConn(c *gin.Context) {
	defer func() {
		if r := recover(); r != nil {
			log.Logger.Error("http flv handleConn panic: ", r)
		}
	}()
	log.Logger.Debug("http-flv server: server: request from ", c.Request.URL)

	url := c.Request.URL.String()
	u := c.Request.URL.Path
	if pos := strings.LastIndex(u, "."); pos < 0 || u[pos:] != ".flv" {
		c.String(http.StatusBadRequest, "invalid path")
		return
	}
	path := strings.TrimSuffix(strings.TrimLeft(u, "/"), ".flv")
	paths := strings.SplitN(path, "/", 2)
	log.Logger.Debug("url:", u, " path:", path, " paths:", paths)
	if len(paths) != 2 {
		c.String(http.StatusBadRequest, "invalid path")
		return
	}

	// 判断视屏流是否发布,如果没有发布,直接返回404
	// TODO: 不间断发送视频流,从rtp拉取音视频.

	c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
	writer, err := NewFLVWriter(paths[0], paths[1], url, c.Writer)
	if err != nil {
		log.Logger.Error(err)
		c.AbortWithStatus(http.StatusInternalServerError)
		return
	}

	// TODO: 需要集成到rtp流中, 在某个rtp流中不停地write开启视频流传输。
	// 这里要注意rtp流要先开启再传输到网页flv上.
	server.handler.HandleWriter(writer)
	writer.Wait()
}
